<?php
/**
 * 报表
 * @author zengsheng
 * @date 2021/01/20
 */

namespace App\Traits;

use GuzzleHttp\Client;

trait Report
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(['base_uri' => config('api.report.url')]);
    }

    protected function execute(callable $handler)
    {
        try {
            return call_user_func($handler);
        } catch (\Exception $e) {
            \Log::debug(
                sprintf('----File: %s , Line: %s , Error: %s', $e->getFile(), $e->getLine(), $e->getMessage())
            );
        }
    }

    protected function okay($code)
    {
        return $code == 200;
    }

    public function token() : string
    {
        return $this->execute(function() {
            return cache()->remember('api.report.token', 86400 * 7, function() {
                return $this->post('/token', [
                    'client_id' => config('api.report.client_id'),
                    'client_secret' => config('api.report.client_secret'),
                    'nonce' => \Illuminate\Support\Str::uuid(),
                    'timestamp' => time(),
                ], function(\stdClass $response) {
                    return $this->okay($response->code) ? $response->result->access_token : '';
                }, false);
            });
        });
    }

    protected function post($url, array $data, \Closure $next = null, $auth = true)
    {
        $options = [];
        if ($auth) {
            $options['headers'] = [
                'Accept' => 'application/json',
                'Authorization' => 'Bearer '.$this->token(),
            ];
        }
        $options['json'] = $data;
        $result = (string) $this->client->request('POST', $url, $options)->getBody();
        return $next(json_decode($result));
    }
}
